package com.auto.learning.activity;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auto.learning.MainActivity;
import com.auto.learning.R;
import com.auto.learning.adapter.TabViewPagerAdapter;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.ReadModeBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.SelectionVo;
import com.auto.learning.event.BookNumChangeEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.fragment.ReadChapterFrgment;
import com.auto.learning.fragment.ReadFinishFragment;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpHelper;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.store.core.StaticReference;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.auto.learning.view.SlidingTabLayout;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

public class ReadBookActivity  extends FragmentActivity{
	
	private final static int GETCACHEDATA_SUCCESS = 1;
	
	private SlidingTabLayout sliding_tabs;
	private ViewPager viewPager;
	ArrayList<Fragment> fragmentArrayList = new ArrayList<Fragment>();
	private String mTabTitle[];
	List<SelectionVo> list = new ArrayList<SelectionVo>();
	int currentPosition = 0;
	private ImageView image_back,image_play,image_tips;
	private String type;
	private int bookId;
	private boolean isPlaying = false;
	private boolean hasSend = false;
	private LinearLayout linear_page;
	private RelativeLayout play_tips;
	private TextView tv_bookname;
	private Map<Integer, View> mapPage = new HashMap<Integer, View>();
	private int canRead;
	private String bookName,slogan,faceImgPlay,faceImg;
	private int needBuy;
	private Handle handler = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case GETCACHEDATA_SUCCESS:
				BookBean bookBean = (BookBean) msg.obj;
				if (bookBean != null) {
					Intent intent = new Intent(ReadBookActivity.this, ReadBookActivity.class);
					intent.putExtra("descList", (Serializable)bookBean.getSectionList());
					intent.putExtra("position", 0);
					String m_type = type;
					if (type.equals("c")) {
						if (TextUtils.isEmpty(bookBean.getSectionList().get(0).getTitle())) {
							m_type = "e";
						}
					}else if (type.equals("e")) {
						if (TextUtils.isEmpty(bookBean.getSectionList().get(0).getTitleEn())) {
							m_type = "c";
						}
					}
					intent.putExtra("type", m_type);
					intent.putExtra("bookId", bookBean.getBookId());
					intent.putExtra("bookName", bookBean.getBookName());
					intent.putExtra("slogan", bookBean.getSlogan());
					intent.putExtra("faceImg", bookBean.getFaceImg());
					intent.putExtra("faceImgPlay", bookBean.getFaceImgPlay());
					intent.putExtra("canRead", bookBean.getCanRead());
					intent.putExtra("needBuy", bookBean.getNeedBuy());
					startActivity(intent); 
					finish();
				}
				break;
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult result = (ResponeResult)msg.obj;
				if (result != null) {
					try {
						ReadModeBean readModeBean = new Gson().fromJson(result.getData(), new TypeToken<ReadModeBean>(){}.getType());
						Cache.cacheReadMode2Local(readModeBean);
						Intent intent = new Intent(ReadBookActivity.this, ReadBookActivity.class);
						intent.putExtra("descList", (Serializable)readModeBean.getSectionList());
						intent.putExtra("position", 0);
						String m_type = type;
						if (type.equals("c")) {
							if (TextUtils.isEmpty(readModeBean.getSectionList().get(0).getTitle())) {
								m_type = "e";
							}
						}else if (type.equals("e")) {
							if (TextUtils.isEmpty(readModeBean.getSectionList().get(0).getTitleEn())) {
								m_type = "c";
							}
						}
						intent.putExtra("type", m_type);
						intent.putExtra("bookId", readModeBean.getBookId());
						intent.putExtra("bookName", readModeBean.getBookName());
						intent.putExtra("slogan", readModeBean.getSlogan());
						intent.putExtra("faceImg", readModeBean.getFaceImg());
						intent.putExtra("faceImgPlay", readModeBean.getFaceImgPlay());
						startActivity(intent); 
						finish();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				break;
			case HttpRequestHelper.SEND_READ_STATUS_SUCCESS:
				ResponeResult m_result = (ResponeResult) msg.obj;
				try {
					if (m_result != null) {
						JSONObject jsonObject = new JSONObject(m_result.getData());
						int isChange = jsonObject.getInt(HttpRequestHelper.BOOKNUM_ISCHANGED);  //1否2是
						int bookNum = jsonObject.getInt("bookNum");
						int userId = (int) SharedPreferencesUtils.getParam(ReadBookActivity.this, HttpRequestHelper.USERID, 0);
						if (isChange == 2) {
							SharedPreferencesUtils.setParam(ReadBookActivity.this,  userId + "_" + HttpRequestHelper.BOOKNUM_ISCHANGED, isChange);
							EventBus.getEventBus("readbook_num_change").post(new BookNumChangeEvent(bookNum,bookId));
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			case HttpRequestHelper.SEND_READ_STATUS_FAIL:
				
				break;
			}
		};
	};
	
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_readbook);
		initData();
		initView();
		registerEvent();
		TemporaryVariable.activities.push(this);
	}
	private void initView(){
		fragmentArrayList.clear();
		mTabTitle = null;
		mapPage.clear();
		play_tips = (RelativeLayout) findViewById(R.id.play_tips);
		image_tips = (ImageView) findViewById(R.id.image_tips);
		if (!(boolean)SharedPreferencesUtils.getParam(this, "has_showUser_read_tips", false)) {
			image_tips.setImageBitmap(CommonMethod.readBitMap(this, R.drawable.play_tips));
			play_tips.setVisibility(View.VISIBLE);	
		}else {
			play_tips.setVisibility(View.GONE);	
		}
		play_tips.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SharedPreferencesUtils.setParam(ReadBookActivity.this, "has_showUser_read_tips", true);
				play_tips.setVisibility(View.GONE);	
			}
		});
		tv_bookname = (TextView) findViewById(R.id.tv_bookname);
		linear_page = (LinearLayout) findViewById(R.id.linear_page);
		image_back = (ImageView) findViewById(R.id.image_back);
		image_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		image_play = (ImageView) findViewById(R.id.image_play);
		int playingBookId[] = MusicPlayManager.getInstance(this).isPlayingBookId();
		if (playingBookId[0] != 0 && playingBookId[0] == bookId) {
			if (playingBookId[2] == 0) 
				image_play.setImageResource(R.drawable.playpause);
			else 
				image_play.setImageResource(R.drawable.play_yuedu);
		}else {
			image_play.setImageResource(R.drawable.play_yuedu);
		}
		
		image_play.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				StatService.onEvent(ReadBookActivity.this, "LogEventReadBookPlayBtnClick", "章节内容右上角的播放按钮");
				int flag = CommonMethod.getNetworkState(ReadBookActivity.this);
				MusicPlayManager manager = MusicPlayManager.getInstance(ReadBookActivity.this);
				int[] ids = manager.isPlayingBookId(); 
				if (ids[1] == list.get(viewPager.getCurrentItem()).getSectionId()) {
					manager.pause();
				}else {
					MusicPlayManager manarger=	MusicPlayManager.getInstance(ReadBookActivity.this);
					if (flag==2 && !TemporaryVariable.downLoadedList.contains(bookId) && manarger.needCheckNet()== false && bookId!=ids[0] && !(boolean)SharedPreferencesUtils.getParam(ReadBookActivity.this, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)) {
						showDialog();
					} else if(flag==0 && !TemporaryVariable.downLoadedList.contains(bookId)){
						CommonMethod.makeNotice(ReadBookActivity.this, getString(R.string.connect_err_io));
					}else{
						ArrayList<BookBean> playList = new ArrayList<BookBean>();
						BookBean bookBean = new BookBean();
						bookBean.setBookId(bookId);
						bookBean.setBookName(bookName);
						bookBean.setSlogan(slogan);
						bookBean.setFaceImgPlay(faceImgPlay);
						bookBean.setFaceImg(faceImg);
						bookBean.setSectionList(list);
						playList.add(bookBean);
						int chapterType = 1;
						if (!TextUtils.isEmpty(type)) {
							if (type.equals("c")) chapterType = 1;
							else if (type.equals("e")) chapterType = 3;
						}
						SharedPreferencesUtils.setParam(ReadBookActivity.this, "chapter_type", chapterType);
						MusicPlayManager.getInstance(ReadBookActivity.this).setPlayList(playList).setNeedContinue(false).setBookAndChapterIds(bookId, list.get(viewPager.getCurrentItem()).getSectionId()).play();
					}
				}
			}
		});
		tv_bookname.setText(bookName+"");
		for (int i = 0; i < list.size(); i++) {
			if ((type.equals("c") && TextUtils.isEmpty(list.get(i).getDescription())) || type.equals("e") && TextUtils.isEmpty(list.get(i).getDescriptionEn())) {
				list.remove(i);
				i--;
			}
		}
		mTabTitle = new String[list.size() + 1];
		for (int i = 0; i < list.size() + 1; i++) {
			mTabTitle[i] = "";
			if (i == list.size()) {
				fragmentArrayList.add(new ReadFinishFragment());
			}else {
				fragmentArrayList.add(type.equals("c") ? ReadChapterFrgment.newInstance(list.get(i).getDescription(),list.get(i).getTitle()) : ReadChapterFrgment.newInstance(list.get(i).getDescriptionEn(),list.get(i).getTitleEn()));
			}
			View view = LayoutInflater.from(this).inflate(R.layout.text_cricle_layout, null);
			view.setLayoutParams(new LinearLayout.LayoutParams(0, CommonMethod.dip2px(this, 30), 1.0f));
			TextView textView = (TextView) view.findViewById(R.id.id_position);
			textView.setText((i+1)+"");
			linear_page.addView(view);
			if (i == currentPosition) {
				view.setVisibility(View.VISIBLE);
			}else {
				if (i == list.size()) {
					view.setVisibility(View.GONE);
				}else {
					view.setVisibility(View.INVISIBLE);
				}
			}
			mapPage.put(i, view);
		}
		linear_page.invalidate();
		TabViewPagerAdapter adapter = new TabViewPagerAdapter(getSupportFragmentManager(), this, fragmentArrayList,mTabTitle);
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		viewPager.setOffscreenPageLimit(list.size());
	    viewPager.setAdapter(adapter);
	    viewPager.setCurrentItem(currentPosition);
	    sliding_tabs = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
	    sliding_tabs.setCustomTabView(R.layout.tab_text, R.id.tv_tab_content,R.color.text_read_bottom_line_color,R.color.text_read_background);
	    sliding_tabs.setShowCricle(true);
	    sliding_tabs.setDistributeEvenly(true);
	    sliding_tabs.setViewPager(viewPager);
	    sliding_tabs.setSelectedIndicatorColors(getResources().getColor(R.color.text_read_bottom_line_color));
	    
	    sliding_tabs.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {   //页面加载完成后
				if (!hasSend && arg0 == fragmentArrayList.size() - 2) {
					hasSend = true;
					sendRead();
				}
				for (int i = 0; i < mapPage.size(); i++) {
					if (arg0 == fragmentArrayList.size() - 1) {
						image_play.setVisibility(View.INVISIBLE);
						mapPage.get(i).setVisibility(View.GONE);
					} else {
						if (arg0 == i) {
							mapPage.get(i).setVisibility(View.VISIBLE);
						} else {
							mapPage.get(i).setVisibility(View.INVISIBLE);
						}
						image_play.setVisibility(View.VISIBLE);
					}
				}
				mapPage.get(fragmentArrayList.size() - 1).setVisibility(View.GONE);
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				
			}
		});
	    
	    if (currentPosition == list.size() - 1) {
	    	hasSend = true;
			sendRead();
		}
	}
	
	public void showDialog() {
		CommonAlertDialog alertDialog = new CommonAlertDialog(ReadBookActivity.this);
		SelectionVo s=	list.get(viewPager.getCurrentItem());
		int size=	s.getProSize()+s.getDoubiSize()+s.getEnSize();
		alertDialog.setTextMessage(String.format(getResources().getString(R.string.play_size_notice),CommonMethod.calculationNum(size)));
		alertDialog.setShowTitle(true);
		String[] a = { getResources().getString(R.string.app_continue), getResources().getString(R.string.app_cancel) };
		alertDialog.setBtns(new DialogListener() {

			@Override
			public void okButtonClick(Dialog dialog) {
				HttpCommonInfo.M_NET_DIALOG_SHOW = false;
				MusicPlayManager manager = MusicPlayManager.getInstance(ReadBookActivity.this);
				manager.setShowNetTips(false);
				ArrayList<BookBean> playList = new ArrayList<BookBean>();
				BookBean bookBean = new BookBean();
				bookBean.setBookId(bookId);
				bookBean.setBookName(bookName);
				bookBean.setSlogan(slogan);
				bookBean.setFaceImgPlay(faceImgPlay);
				bookBean.setFaceImg(faceImg);
				bookBean.setSectionList(list);
				playList.add(bookBean);
				manager.setPlayList(playList).setNeedContinue(false).setBookAndChapterIds(bookId, list.get(viewPager.getCurrentItem()).getSectionId()).play();
				dialog.dismiss();
			}

			@Override
			public void cancelButtonClick(Dialog dialog) {
				dialog.dismiss();
				
			
			}

			@Override
			public void otherButtonClick(Dialog dialog) {
				dialog.dismiss();
				HttpCommonInfo.M_NET_DIALOG_SHOW = false;
				MusicPlayManager.getInstance(ReadBookActivity.this).setShowNetTips(true);
			}
		}, a);
		alertDialog.show();
	}

	public void sendRead(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, String.valueOf(bookId)));
//		HttpRequestHelper.executeHttpData(this, HttpRequestHelper.BOOK_READ, params, handle, -9999);
		HttpRequestHelper.sendBookReadStatus(this, HttpRequestHelper.BOOK_READ, params, handler, HttpRequestHelper.SEND_READ_STATUS_SUCCESS, HttpRequestHelper.SEND_READ_STATUS_FAIL, bookId);
	}
	
	private void initData(){
		list.clear();
		Intent intent = getIntent();
		list = (List<SelectionVo>) intent.getSerializableExtra("descList");
		currentPosition = intent.getIntExtra("position", 0);
		type = intent.getStringExtra("type");
		bookId = intent.getIntExtra("bookId", 0);
		bookName = intent.getStringExtra("bookName");
		slogan = intent.getStringExtra("slogan");
		canRead=intent.getIntExtra("canRead", 2);
		needBuy=intent.getIntExtra("needBuy", 1);
		faceImgPlay = intent.getStringExtra("faceImgPlay");
		faceImg = intent.getStringExtra("faceImg");
		if (bookId > 0) {
			EventBus.getEventBus("m_refresh_collect_sort").post(bookId);
		}
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		initData();
		initView();
	}
	
	@Override
	protected void onDestroy() {
		TemporaryVariable.activities.removeElement(this);
		unRegisterEvent();
		super.onDestroy();
	}
	
	@Subscribe
	public void onEventPlayStute(Boolean isPlaying){
		this.isPlaying = isPlaying;
		if (isPlaying && bookId == MusicPlayManager.getInstance(this).isPlayingBookId()[0]) {
			image_play.setImageResource(R.drawable.playpause);
		}else {
			image_play.setImageResource(R.drawable.play_yuedu);
		}
	}
	
	public void registerEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).register(this);
	}
	
	public void unRegisterEvent(){
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).unregister(this);
	}
	

	
	public int getBookId() {
		return bookId;
	}
	
	public String getBookName() {
		return bookName;
	}
	
	public String getSlogan() {
		return slogan;
	}
	
	public String getFaceImgPlay() {
		return faceImgPlay;
	}
	
	public String getFaceImg() {
		return faceImg;
	}
	
	public void refreshUIData(final int s_bookId){
		
		Pool.getPool().execute(new Runnable() {
			
			@Override
			public void run() {
				try {
					BookBean bookBean = StaticReference.mutilDBSupport.getDao(BookBean.class).queryForId(s_bookId);
					if (bookBean == null|| (bookBean != null && (isEmpty(bookBean.getAbout()) || isEmpty(bookBean.getGoldWord())))) {
						// 请求
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair(HttpRequestHelper.USERID,String.valueOf(SharedPreferencesUtils.getParam(ReadBookActivity.this,HttpRequestHelper.USERID, 0))));
						params.add(new BasicNameValuePair(HttpRequestHelper.BOOKID, String.valueOf(s_bookId)));
						HttpEntity entity = HttpHelper.getInfoByPost(HttpRequestHelper.READ_MODE, params,ReadBookActivity.this);
						String _result = HttpHelper.entity2String(entity);
						JSONObject jsonResult = new JSONObject(_result);
						JSONObject result = jsonResult.getJSONObject(HttpCommonInfo.RESULT);
						int code = result.getInt(HttpCommonInfo.RESULT_CODE);
						String msg = result.getString(HttpCommonInfo.RESULT_MSG);
						ResponeResult responeResult = new ResponeResult();
						responeResult.setCode(code);
						responeResult.setMsg(msg);
						if (code == 0) {
							responeResult.setData(jsonResult.getString(HttpCommonInfo.DATA));
							handler.obtainMessage(HttpRequestHelper.GETDATA_SUCCESS,responeResult).sendToTarget();
						} else {
							handler.sendEmptyMessage(-100);
						}
					} else {
						try {
							List<SelectionVo> selectionVos = StaticReference.mutilDBSupport.getDao(SelectionVo.class).queryForEq("bookId", s_bookId);
							bookBean.setSectionList(selectionVos);
							handler.obtainMessage(GETCACHEDATA_SUCCESS,bookBean).sendToTarget();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					handler.obtainMessage(-100, getResources().getString(R.string.connect_err_io)).sendToTarget();
				}
			}
		});
	}
	
	boolean isEmpty(String txt){
		return TextUtils.isEmpty(txt);
	}
}
